#-*- codeing = utf-8 -*-
#@Time : 2020/9/17 11:54
#@Author : 阳某
#@File : 淘宝.py
#@Software : PyCharm
import csv
import re

from selenium import webdriver
import time
from selenium.webdriver import ActionChains
from selenium.webdriver import ChromeOptions
def search(key):
    driver.get("https://www.taobao.com/")
    driver.find_element_by_id('q').send_keys(key)
    time.sleep(1)
    driver.find_element_by_class_name('btn-search').click()
    driver.implicitly_wait(10)  #隐示等待 10秒   等待页面渲染完之后就不在等待
    driver.maximize_window()    #最大化浏览器

    # #解决登录
    driver.find_element_by_xpath('//*[@id="fm-login-id"]').send_keys('tb480426989')     #用户名
    time.sleep(1)
    driver.find_element_by_xpath('//*[@id="fm-login-password"]').send_keys('xxxxx')      #密码
    time.sleep(2)
    #  解决滑块
    # login = driver.find_element_by_xpath('//*[@id="nc_1_n1z"]')     #滑块
    # action = ActionChains(driver)
    # action.click_and_hold(on_element= login)
    # action.move_by_offset(xoffset=258,yoffset=0)    #计算
    # action.pause(2).release().perform()   #pause表示多少时间内执行完，release表示释放鼠标，perform表示立即执行动作链
    driver.find_element_by_xpath('//*[@id="login-form"]/div[4]/button').click()     #登录按钮
    driver.implicitly_wait(10)

    page = driver.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[1]').text
    page_num = re.findall('(\d+)',page)[0]

    return page_num

def get_data():
    div_list = driver.find_elements_by_xpath('//*[@id="mainsrp-itemlist"]/div/div/div[1]/div')
    for div in div_list:
        title = div.find_element_by_xpath('.//div[@class="row row-2 title"]/a').text
        price = div.find_element_by_xpath('.//strong').text
        nums = div.find_element_by_xpath('.//div[@class="deal-cnt"]').text
        shop_name = div.find_element_by_xpath('.//div[@class="shop"]/a').text
        shop_add = div.find_element_by_xpath('.//div[@class="location"]').text
        print(title, price, nums, shop_name ,shop_name, shop_add ,sep = '|')
        with open('../data.csv', 'a', encoding='utf-8-sig', newline='')as csvfile:
            csvwriter = csv.writer(csvfile,delimiter = ',')
            csvwriter.writerow([title, price, nums, shop_name ,shop_name, shop_add])    #传入序列化数据
def main():
    print('正在爬取第一页数据')
    page = search(keyword)
    get_data()
    # # 第一页s为0，第二页为44，第三页为88
    # page_num = 1    #page_num*44
    # while page_num != page:
    #     print('*'*100)
    #     print('正在打印第%s页'%(page_num+1))
    #     print('*'*100)
    #     # https://s.taobao.com/search?q=U盘&s=44
    #     driver.get('https://s.taobao.com/search?q={}&s={}'.format(keyword,page_num * 44))
    #     driver.implicitly_wait(10)
    #     get_data()
    #     page_num += 1
    # driver.quit()
if __name__ == '__main__':
    '''
     # # chrome_options 初始化选项
    # chrome_options = webdriver.ChromeOptions()
    # # 设置浏览器初始 位置x,y & 宽高x,y
    # chrome_options.add_argument(f'--window-position={217},{172}')
    # chrome_options.add_argument(f'--window-size={1200},{1000}')
    # 关闭自动测试状态显示 // 会导致浏览器报：请停用开发者模式
    # window.navigator.webdriver还是返回True,当返回undefined时应该才可行。
    '''
    # 关闭自动测试状态显示 // 会导致浏览器报：请停用开发者模式
    # window.navigator.webdriver还是返回True,当返回undefined时应该才可行。
    option = ChromeOptions()
    option.add_experimental_option("excludeSwitches", ['enable-automation'])
    # 如何实现让selenium规避被检测的风险
    driver = webdriver.Chrome(options = option)
    # 通过浏览器的dev_tool在get页面钱将.webdriver属性改为"undefined"
    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {                           #直接滑块消失
        "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})""",
    })
    keyword = input('请输入你要爬取的商品名称：')
    main()